package mess;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class LeeCode_1487 {
    public static void main(String[] args) {
        System.out.println(Arrays.toString(getFolderNames(new String[]{"a", "a", "a", "a", "a","a","a","a","a","a","a","a"})));
        //System.out.println(Arrays.toString(getFolderNames2(new String[]{"kaido", "kaido(1)", "kaido", "kaido(1)"})));
    }

    private static String[] getFolderNames(String[] names) {
        Set<String> set = new HashSet();
        for (int i = 0; i < names.length; i++) {
            boolean flag = false;
            while (true) {
                if (set.contains(names[i])) {
                    if (!flag) {
                        names[i] = names[i] + "(" + 1 + ")";
                        flag = true;
                    } else {
                        int start = -1;
                        for (int j = names[i].length() - 1; j >= 0; j--) {
                            if (names[i].charAt(j) == '('){
                                start = j;
                                break;
                            }
                        }
                        if (start != -1){
                            String prefix = names[i].substring(0, start + 1);
                            String numStr = names[i].substring(start + 1, names[i].length() - 1);
                            int num = Integer.parseInt(numStr);
                            names[i] = prefix + (num + 1) + ")";
                        }
                    }
                } else {
                    set.add(names[i]);
                    break;
                }
            }
        }
        return names;
    }

    private static String[] getFolderNames2(String[] names) {
        Set<String> set = new HashSet();
        for (int i = 0; i < names.length; i++) {
            while (true) {
                int len1 = set.size();
                set.add(names[i]);
                int len2 = set.size();
                if (len1 == len2) {
                    if (names[i].length() > 3) {
                        String suffix = names[i].substring(names[i].length() - 3, names[i].length());
                        if (suffix.charAt(0) == '(' && suffix.charAt(2) == ')') {
                            String prefix = names[i].substring(0, names[i].length() - 3);
                            String newSuffix = "(" + (suffix.charAt(1) - 47) + ")";
                            names[i] = prefix + newSuffix;
                        } else {
                            names[i] = names[i] + "(" + 1 + ")";
                        }
                    } else {
                        names[i] = names[i] + "(" + 1 + ")";
                    }
                } else
                    break;
            }
        }
        return names;
    }


}
